package com.pazl.check.utils;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.pazl.check.constants.Constants;

/**
 * 字符串帮助类
 *
 */
public class StringUtil {

	private static final String MASK = "[^ -()]";
	private static final String MASK_CHAR = "*";

	public static boolean isEmpty(Object pObj) {
		if (pObj == null) {
			return true;
		}
		if (pObj == "") {
			return true;
		}
		if ((pObj instanceof String)) {
			if (((String) pObj).length() == 0) {
				return true;
			}
		} else if ((pObj instanceof Collection)) {
			if (((Collection<?>) pObj).size() == 0) {
				return true;
			}
		} else if (((pObj instanceof Map)) && (((Map<?, ?>) pObj).size() == 0)) {
			return true;
		}

		return false;
	}

	public static boolean isNotEmpty(Object pObj) {
		if (pObj == null) {
			return false;
		}
		if (pObj == "") {
			return false;
		}
		if ((pObj instanceof String)) {
			if (((String) pObj).length() == 0) {
				return false;
			}
		} else if ((pObj instanceof Collection)) {
			if (((Collection<?>) pObj).size() == 0) {
				return false;
			}
		} else if (((pObj instanceof Map)) && (((Map<?, ?>) pObj).size() == 0)) {
			return false;
		}

		return true;
	}

	public static String capitalize(String str) {
		int strLen;
		if ((str == null) || ((strLen = str.length()) == 0)) {
			return str;
		}
		int firstCodepoint = str.codePointAt(0);
		int newCodePoint = Character.toTitleCase(firstCodepoint);
		if (firstCodepoint == newCodePoint) {
			return str;
		}

		int[] newCodePoints = new int[strLen];
		int outOffset = 0;
		newCodePoints[(outOffset++)] = newCodePoint;
		for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen;) {
			int codepoint = str.codePointAt(inOffset);
			newCodePoints[(outOffset++)] = codepoint;
			inOffset += Character.charCount(codepoint);
		}
		return new String(newCodePoints, 0, outOffset);
	}

	/**
	 * 正则匹配
	 * 
	 * @param regex
	 * @param str
	 * @return
	 */
	public static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	public static String getString(byte[] bytes) {
		try {
			return new String(bytes, Constants.DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	public static byte[] getBytes(String str) {
		try {
			return str.getBytes(Constants.DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	public static String mask(String str, int begin, int end) {
		return str.substring(0, begin) + str.substring(begin, end).replaceAll(MASK, MASK_CHAR)
				+ str.substring(end, str.length());
	}
}
